package com.sike.service;

import com.sike.entity.Mail;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


@Service
public class MailService {
    @Autowired
    private JavaMailSender javaMailSender;

    //发送简单邮件
    public void sendSimpleMailMessage(Mail mail){
        System.out.println(mail);
        //封装simpleMailMessage对象
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom(mail.getFrom());
        simpleMailMessage.setTo(mail.getTo());
        simpleMailMessage.setCc(mail.getCc());
        simpleMailMessage.setSubject(mail.getSubject());
        simpleMailMessage.setText(mail.getContent());
        javaMailSender.send(simpleMailMessage); //发送
    }

    //发送带附件的邮件
    public void sendMailWithFile(Mail mail){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mail.getFrom());
            mimeMessageHelper.setTo(mail.getTo());
            mimeMessageHelper.setCc(mail.getCc());
            mimeMessageHelper.setSubject(mail.getSubject());
            mimeMessageHelper.setText(mail.getContent());
            //添加附件
            mimeMessageHelper.addAttachment(mail.getFile().getName(),mail.getFile());
            javaMailSender.send(mimeMessage);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }

    @Autowired
    TemplateEngine templateEngine;
    //发送模板邮件
    public void sendTempateMail(Mail mail,String username,String orderNo,String amount,String mobile){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mail.getFrom());
            mimeMessageHelper.setTo(mail.getTo());
            mimeMessageHelper.setCc(mail.getCc());
            mimeMessageHelper.setSubject(mail.getSubject());
            Context context=new Context();
            context.setVariable("username",username);
            context.setVariable("orderNo",orderNo);
            context.setVariable("amount",amount);
            context.setVariable("mobile",mobile);
            //合并模板与数据
            String content= templateEngine.process("templateMail.html",context);
            mimeMessageHelper.setText(content,true);
            javaMailSender.send(mimeMessage);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }



}

